package com.peppa.common.grayconfig.Strategy.factory;

import com.peppa.common.grayconfig.Strategy.Strategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.*;

public class StrategyFactory {
    private ApplicationContext applicationContext;
    private static HashMap<String, Strategy> strategyHashMap = new HashMap<>();
    private static List<Strategy> strategyList = new ArrayList<>();
    final Logger logger = LoggerFactory.getLogger(getClass());
    public StrategyFactory(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }
    public void init(){
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(AnnoStrategy.class);//获取全部ControllerBean
        Set<Map.Entry<String, Object>> entries = beans.entrySet();//遍历Bean
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> map = iterator.next();
            Object bean = map.getValue();

            Class<?> aClass = map.getValue().getClass();
            logger.info("Strategy.aClass"+aClass);
            if ( map.getValue() instanceof Strategy){
                Strategy strategy = (Strategy)bean;
                String strategyname = strategy.getName();
                logger.info("Strategy. strategyname："+strategyname);
                StrategyFactory.strategyHashMap.put(strategyname,strategy);
                strategyList.add(strategy);
            }
//                try {
//                    Method method = aClass.getMethod("getName");
//                    String strategyname = (String) method.invoke(null);
//
//                }catch (Exception e){
//                    e.printStackTrace();
//                }

        }
        Collections.sort(strategyList);
        logger.info("StrategyFactory.strategyHashMap.size"+ StrategyFactory.strategyHashMap.size());
    }
    public static Strategy getStrategy(String name){
        return strategyHashMap.get(name);
    }

    /**
     * @return 排序的策略列表
     */
    public static List<Strategy> getAllStrategy(){
        return strategyList;
    }
}
